﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Util.Extension;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CRMGroupController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        public CRMGroupController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmGroups
                           select new
                           {
                               id = y.Id,
                               names = y.Name,
                               sort = y.Sort,
                               state = y.State,
                               creator = y.Creator,
                               createDate = y.CreateDate,
                               remark = y.Remark
                           };
                res.Code = 0;
                res.Count = data.Count();
                if (page == 0 && limit == 0)
                {
                    res.Data = await data.OrderBy(k => k.sort).ToListAsync();
                }
                else
                {
                    res.Data = await data.OrderBy(k => k.sort).Skip((page - 1) * limit).Take(limit).ToListAsync();
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }


        #region 添加
        public IActionResult Create()
        {
            int? Sort = 1;
            if (_context.CrmGroups.Count() > 0)
            {
                Sort = _context.CrmGroups.Max(k => k.Sort) + 1;
            }
            ViewBag.Sort = Sort;
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(CrmGroup model)
        {
            Result res = new Result();
            try
            {
                if (!ToExists(model.Name))
                {
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTime.Now;
                    model.State = 1;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "submitFail";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            CrmGroup currency = await _context.CrmGroups.FindAsync(id);
            if (currency == null)
            {
                return NotFound();
            }
            return View(currency);
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(CrmGroup item)
        {
            Result res = new Result();
            try
            {
                if (!ToExists(item.Name, item.Id))
                {
                    CrmGroup model = await _context.CrmGroups.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.Name = item.Name;
                        model.Sort = item.Sort;
                        model.Remark = item.Remark;

                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "submitFail";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "submitFail";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                CrmGroup currency = await _context.CrmGroups.FindAsync(id);

                currency.State = intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                CrmGroup currency = await _context.CrmGroups.FindAsync(id);

                _context.CrmGroups.Remove(currency);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<CrmGroup> dataList = await _context.CrmGroups.Where(k => list.Contains(k.Id)).ToListAsync();
                foreach (CrmGroup model in dataList)
                {
                    _context.CrmGroups.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">名称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool ToExists(string Name, int id = 0)
        {
            if (id == 0)
                return _context.CrmGroups.Any(e => e.Name == Name);
            else
                return _context.CrmGroups.Any(e => e.Id != id && e.Name == Name);
        }
        #endregion
    }
}
